// src/components/fortune\ConvertibleBond.tsx
import React from 'react';
import { observer } from 'mobx-react-lite';
import { 
  Card, 
  Table, 
  Tag, 
  Statistic,
  Row, 
  Col,
  Timeline,
  Descriptions,
  Space,
  Typography,
  Button,
  DatePicker,
  Select,
  Divider
} from 'antd';
import { 
  ArrowLeftOutlined, 
  RiseOutlined,
  FallOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ReloadOutlined,
  FilterOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import styled from '@emotion/styled';
import type { ColumnsType } from 'antd/es/table';
import { useStore } from '../../stores';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

// 类型定义
interface TradeRecord {
  key: string;
  date: string;
  time: string;
  bondCode: string;
  bondName: string;
  operationType: '建底仓' | '加仓' | '卖出' | '减仓';
  price: number;
  quantity: number;
  amount: number;
  reason: string;
  indicators: string;
  status: 'success' | 'failure' | 'pending';
  profit?: number;
}

interface DailySummary {
  date: string;
  totalCapital: number;
  dailyProfit: number;
  dailyReturnRate: number;
  successCount: number;
  failureCount: number;
  bestTrade: string;
  worstTrade: string;
  mood: string;
  improvement: string;
}

// Styled Components
const OperationContainer = styled.div`
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  position: relative;
`;

const BackButton = styled(Button)`
  position: absolute;
  top: 20px;
  left: 20px;
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.5);
    color: #fff;
  }
`;

const ContentWrapper = styled.div`
  max-width: 1400px;
  margin: 0 auto;
  padding-top: 60px;
`;

const StyledCard = styled(Card)`
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  margin-bottom: 24px;
  
  .ant-card-body {
    padding: 24px;
  }
`;

const PageHeader = styled.div`
  text-align: center;
  margin-bottom: 32px;
  
  h1 {
    margin-bottom: 8px;
    color: #fff;
    font-weight: 600;
  }
  
  .subtitle {
    color: rgba(255, 255, 255, 0.8);
    font-size: 16px;
  }
`;

const FilterSection = styled.div`
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  flex-wrap: wrap;
  align-items: center;
`;

const FilterItem = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  
  .ant-picker, .ant-select {
    min-width: 200px;
  }
`;

const StatsCard = styled(Card)`
  border-radius: 8px;
  text-align: center;
  border: none;
  
  .ant-statistic-content {
    font-weight: 600;
  }
`;

// 修改CSS语法错误
const SuccessTag = styled(Tag)`
  background: #f6ffed;
  border-color: #b7eb8f;
  color: #52c41a;
`;

const FailureTag = styled(Tag)`
  background: #fff2f0;
  border-color: #ffccc7;
  color: #ff4d4f;
`;

const PendingTag = styled(Tag)`
  background: #f0f5ff;
  border-color: #adc6ff;
  color: #2f54eb;
`;

const OperationTag = styled(Tag)<{ type: string }>`
  background: ${props => 
    props.type === '建底仓' ? '#e6f7ff' : 
    props.type === '加仓' ? '#f6ffed' : 
    props.type === '卖出' ? '#fff7e6' : '#fff2f0'};
  border-color: ${props => 
    props.type === '建底仓' ? '#91d5ff' : 
    props.type === '加仓' ? '#b7eb8f' : 
    props.type === '卖出' ? '#ffd591' : '#ffccc7'};
  color: ${props => 
    props.type === '建底仓' ? '#1890ff' : 
    props.type === '加仓' ? '#52c41a' : 
    props.type === '卖出' ? '#fa8c16' : '#ff4d4f'};
`;

const TimelineItem = styled(Timeline.Item)`
  .ant-timeline-item-content {
    font-size: 14px;
  }
`;

// 修复CSS语法错误：添加缺失的分号
const IndicatorBadge = styled.span`
  display: inline-block;
  padding: 2px 8px;
  background: #f0f5ff;
  border-radius: 4px;
  margin: 2px;
  font-size: 12px;
  color: #2f54eb;
`;

// 响应式样式
const MobileWrapper = styled.div`
  @media (max-width: 768px) {
    padding: 16px;
    
    button.ant-btn {
      top: 16px;
      left: 16px;
    }
    
    div {
      padding-top: 50px;
    }
    
    div {
      flex-direction: column;
      align-items: stretch;
    }
    
    .ant-col {
      margin-bottom: 16px;
    }
  }
`;

const ConvertibleBond: React.FC = () => {
  const navigate = useNavigate();
  const store = useStore();

  const handleBack = () => {
    navigate(-1);
  };

  // 模拟数据
  const tradeRecords: TradeRecord[] = [
    {
      key: '1',
      date: '2024-01-20',
      time: '10:30',
      bondCode: '127021',
      bondName: '英力转债',
      operationType: '加仓',
      price: 129.22,
      quantity: 50,
      amount: -6461,
      reason: '价格触网格点，跌破BOLL下轨',
      indicators: 'KDJ<20金叉, MACD绿柱衰竭, BOLL下轨',
      status: 'success',
      profit: 0.7
    },
    {
      key: '2',
      date: '2024-01-20',
      time: '10:50',
      bondCode: '127021',
      bondName: '英力转债',
      operationType: '卖出',
      price: 130.15,
      quantity: 50,
      amount: 6507.5,
      reason: '价格达盈利目标，反弹至BOLL中轨',
      indicators: 'KDJ>80死叉, MACD红柱缩短',
      status: 'success',
      profit: 0.7
    },
    {
      key: '3',
      date: '2024-01-20',
      time: '13:30',
      bondCode: '127021',
      bondName: '英力转债',
      operationType: '加仓',
      price: 128.45,
      quantity: 50,
      amount: -6422.5,
      reason: '价格再次触及加仓网格，指标超卖',
      indicators: 'KDJ<0金叉, BOLL下轨',
      status: 'pending'
    },
    {
      key: '4',
      date: '2024-01-20',
      time: '14:40',
      bondCode: '127021',
      bondName: '英力转债',
      operationType: '卖出',
      price: 128.90,
      quantity: 50,
      amount: 6445,
      reason: '尾盘风险控制，保本卖出',
      indicators: '反弹乏力，临近收盘',
      status: 'success',
      profit: 0.35
    },
    {
      key: '5',
      date: '2024-01-19',
      time: '11:20',
      bondCode: '123456',
      bondName: '测试转债',
      operationType: '建底仓',
      price: 130.00,
      quantity: 100,
      amount: -13000,
      reason: '开盘企稳，价格在BOLL中轨获支撑',
      indicators: 'KDJ中位, MACD绿柱缩短',
      status: 'failure',
      profit: -1.2
    }
  ];

  const dailySummaries: DailySummary[] = [
    {
      date: '2024-01-20',
      totalCapital: 100000,
      dailyProfit: 525,
      dailyReturnRate: 0.53,
      successCount: 3,
      failureCount: 1,
      bestTrade: '英力转债在129.22的加仓，严格按计划执行，指标共振，买点精准',
      worstTrade: '尾盘冲动买入XX转债，违反了临近收盘不开新仓的纪律',
      mood: '上午冷静，下午因一笔小亏损略有急躁',
      improvement: '1. 严格遵守交易时间纪律。2. 当日盈利达标后，应以防守为主'
    },
    {
      date: '2024-01-19',
      totalCapital: 100000,
      dailyProfit: -320,
      dailyReturnRate: -0.32,
      successCount: 2,
      failureCount: 2,
      bestTrade: '早盘精准识别反弹信号，及时买入',
      worstTrade: '追高买入被套，未等指标确认',
      mood: '整体急躁，急于挽回损失',
      improvement: '1. 避免情绪化交易。2. 等待指标充分确认再操作'
    }
  ];

  const bondOptions = [
    { value: 'all', label: '全部转债' },
    { value: '127021', label: '英力转债' },
    { value: '123456', label: '测试转债' }
  ];

  const columns: ColumnsType<TradeRecord> = [
    {
      title: '日期/时间',
      dataIndex: 'date',
      key: 'dateTime',
      render: (date: string, record: TradeRecord) => (
        <div>
          <div>{date}</div>
          <Text type="secondary">{record.time}</Text>
        </div>
      ),
      sorter: (a, b) => a.date.localeCompare(b.date) || a.time.localeCompare(b.time)
    },
    {
      title: '转债信息',
      dataIndex: 'bondName',
      key: 'bondInfo',
      render: (name: string, record: TradeRecord) => (
        <div>
          <div>{name}</div>
          <Text type="secondary">{record.bondCode}</Text>
        </div>
      )
    },
    {
      title: '操作类型',
      dataIndex: 'operationType',
      key: 'operationType',
      render: (type: string) => (
        <OperationTag type={type}>{type}</OperationTag>
      )
    },
    {
      title: '价格/数量',
      key: 'priceQuantity',
      render: (record: TradeRecord) => (
        <div>
          <div>¥{record.price}</div>
          <Text type="secondary">{record.quantity}张</Text>
        </div>
      )
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => (
        <Text strong type={amount > 0 ? 'success' : 'danger'}>
          {amount > 0 ? '+' : ''}{amount.toLocaleString()}
        </Text>
      )
    },
    {
      title: '盈亏',
      dataIndex: 'profit',
      key: 'profit',
      render: (profit: number | undefined) => {
        if (profit === undefined) return <Text>-</Text>;
        return (
          <Text strong type={profit > 0 ? 'success' : profit < 0 ? 'danger' : 'secondary'}>
            {profit > 0 ? '+' : ''}{profit}%
          </Text>
        );
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        if (status === 'success') return <SuccessTag>成功</SuccessTag>;
        if (status === 'failure') return <FailureTag>失败</FailureTag>;
        return <PendingTag>进行中</PendingTag>;
      }
    },
    {
      title: '交易理由',
      dataIndex: 'reason',
      key: 'reason',
      ellipsis: true
    },
    {
      title: '指标状态',
      dataIndex: 'indicators',
      key: 'indicators',
      render: (indicators: string) => (
        <div>
          {indicators.split(', ').map((indicator, index) => (
            <IndicatorBadge key={index}>{indicator}</IndicatorBadge>
          ))}
        </div>
      )
    }
  ];

  const getStatusIcon = (status: string) => {
    return status === 'success' ? 
      <CheckCircleOutlined style={{ color: '#52c41a' }} /> : 
      <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
  };

  return (
    <MobileWrapper>
      <OperationContainer>
        <BackButton 
          type="text" 
          icon={<ArrowLeftOutlined />} 
          onClick={handleBack}
        >
          返回
        </BackButton>
        
        <ContentWrapper>
          <PageHeader>
            <Title level={1}>可转债T+0交易日志</Title>
            <Text className="subtitle">记录每一笔交易，持续优化投资策略</Text>
          </PageHeader>

          {/* 统计概览 */}
          <StyledCard>
            <Title level={3}>今日概览</Title>
            <Row gutter={16}>
              <Col xs={12} sm={6}>
                <StatsCard>
                  <Statistic
                    title="总本金"
                    value={100000}
                    prefix="¥"
                    valueStyle={{ color: '#1890ff' }}
                  />
                </StatsCard>
              </Col>
              <Col xs={12} sm={6}>
                <StatsCard>
                  <Statistic
                    title="当日盈亏"
                    value={525}
                    prefix={<RiseOutlined />}
                    valueStyle={{ color: '#52c41a' }}
                  />
                </StatsCard>
              </Col>
              <Col xs={12} sm={6}>
                <StatsCard>
                  <Statistic
                    title="当日收益率"
                    value={0.53}
                    suffix="%"
                    valueStyle={{ color: '#52c41a' }}
                  />
                </StatsCard>
              </Col>
              <Col xs={12} sm={6}>
                <StatsCard>
                  <Statistic
                    title="成功率"
                    value={75}
                    suffix="%"
                    valueStyle={{ color: '#52c41a' }}
                  />
                </StatsCard>
              </Col>
            </Row>
          </StyledCard>

          {/* 操作时间线 */}
          <StyledCard>
            <Title level={3}>今日操作时间线</Title>
            <Timeline>
              <TimelineItem dot={getStatusIcon('success')}>
                <Space direction="vertical" size={0}>
                  <Text strong>10:30 - 第一次加仓机会</Text>
                  <Text type="secondary">价格从130元震荡下跌至129.22元，触及第一个加仓网格点</Text>
                  <div>
                    <IndicatorBadge>KDJ: J值&lt;10超卖</IndicatorBadge>
                    <IndicatorBadge>BOLL: 触及下轨</IndicatorBadge>
                    <IndicatorBadge>MACD: 绿柱缩短</IndicatorBadge>
                  </div>
                  <Text type="success">操作: 买入20%资金</Text>
                </Space>
              </TimelineItem>
              <TimelineItem dot={getStatusIcon('success')}>
                <Space direction="vertical" size={0}>
                  <Text strong>10:50 - 第一次卖出机会</Text>
                  <Text type="secondary">价格反弹至130.15元，触及卖出点</Text>
                  <div>
                    <IndicatorBadge>KDJ: J值&gt;90超买</IndicatorBadge>
                    <IndicatorBadge>MACD: 红柱缩短</IndicatorBadge>
                  </div>
                  <Text type="success">操作: 卖出加仓部分，锁定0.7%利润</Text>
                </Space>
              </TimelineItem>
              <TimelineItem dot={getStatusIcon('success')}>
                <Space direction="vertical" size={0}>
                  <Text strong>13:30 - 第二次加仓机会</Text>
                  <Text type="secondary">价格再次回落至128.45元，触及加仓网格</Text>
                  <div>
                    <IndicatorBadge>KDJ: J值为负</IndicatorBadge>
                    <IndicatorBadge>BOLL: 跌破下轨</IndicatorBadge>
                  </div>
                  <Text type="success">操作: 再次买入20%资金</Text>
                </Space>
              </TimelineItem>
              <TimelineItem dot={getStatusIcon('success')}>
                <Space direction="vertical" size={0}>
                  <Text strong>14:40 - 尾盘处理</Text>
                  <Text type="secondary">价格反弹乏力，仅回到128.90元</Text>
                  <Text type="warning">操作: 保本卖出加仓部分，控制隔夜风险</Text>
                </Space>
              </TimelineItem>
            </Timeline>
          </StyledCard>

          {/* 交易记录表格 */}
          <StyledCard>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
              <Title level={3} style={{ margin: 0 }}>交易记录明细</Title>
              <Space>
                <FilterSection>
                  <FilterItem>
                    <FilterOutlined />
                    <RangePicker 
                      placeholder={['开始日期', '结束日期']}
                    />
                  </FilterItem>
                  <FilterItem>
                    <Text>转债:</Text>
                    <Select 
                      style={{ minWidth: 120 }}
                    >
                      {bondOptions.map(option => (
                        <Option key={option.value} value={option.value}>
                          {option.label}
                        </Option>
                      ))}
                    </Select>
                  </FilterItem>
                  <Button icon={<ReloadOutlined />}>重置</Button>
                </FilterSection>
              </Space>
            </div>

            <Table 
              columns={columns} 
              dataSource={tradeRecords}
              pagination={{ pageSize: 10 }}
              scroll={{ x: 800 }}
            />
          </StyledCard>

          {/* 每日总结 */}
          <StyledCard>
            <Title level={3}>每日总结与反思</Title>
            {dailySummaries.map((summary, index) => (
              <div key={summary.date} style={{ marginBottom: index < dailySummaries.length - 1 ? 24 : 0 }}>
                <Descriptions 
                  title={`${summary.date} 交易总结`} 
                  bordered 
                  column={{ xs: 1, sm: 2, md: 3 }}
                  size="small"
                >
                  <Descriptions.Item label="总本金">¥{summary.totalCapital.toLocaleString()}</Descriptions.Item>
                  <Descriptions.Item label="当日盈亏">
                    <Text type={summary.dailyProfit > 0 ? 'success' : 'danger'}>
                      {summary.dailyProfit > 0 ? '+' : ''}¥{summary.dailyProfit}
                    </Text>
                  </Descriptions.Item>
                  <Descriptions.Item label="当日收益率">
                    <Text type={summary.dailyReturnRate > 0 ? 'success' : 'danger'}>
                      {summary.dailyReturnRate > 0 ? '+' : ''}{summary.dailyReturnRate}%
                    </Text>
                  </Descriptions.Item>
                  <Descriptions.Item label="成功交易">{summary.successCount}次</Descriptions.Item>
                  <Descriptions.Item label="失败交易">{summary.failureCount}次</Descriptions.Item>
                  <Descriptions.Item label="成功率">
                    {((summary.successCount / (summary.successCount + summary.failureCount)) * 100).toFixed(1)}%
                  </Descriptions.Item>
                  <Descriptions.Item label="今日最佳交易" span={3}>
                    {summary.bestTrade}
                  </Descriptions.Item>
                  <Descriptions.Item label="今日最差交易" span={3}>
                    {summary.worstTrade}
                  </Descriptions.Item>
                  <Descriptions.Item label="心态评估" span={3}>
                    {summary.mood}
                  </Descriptions.Item>
                  <Descriptions.Item label="明日计划/改进点" span={3}>
                    {summary.improvement}
                  </Descriptions.Item>
                </Descriptions>
                {index < dailySummaries.length - 1 && <Divider />}
              </div>
            ))}
          </StyledCard>
        </ContentWrapper>
      </OperationContainer>
    </MobileWrapper>
  );
};

export default observer(ConvertibleBond);